import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000, // request timeout
});

service.interceptors.request.use(
  (config) => {
    config.headers["token"] = getToken();
    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code == 1) {
      if (!res.msg) {
        res.msg = "操作成功";
      }

      return res;
    } else {
      if (!res.msg) {
        res.msg = "失败，请刷新后重试";
      }
      Message({
        message: res.msg,
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(res);
    }
  },
  (error) => {
    console.log("error", error);

    var ret = error.response.data;

    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    console.log(error, "request error");

    if (ret["code"] == 403 || ret["code"] == 401) {
      MessageBox.confirm("登录信息已过期，请重新登录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        })
        .catch(() => {});
    }
    return Promise.reject(error);
  }
);

export default service;
